require("../util.js");
require("../component/components.js");
require("../../jsMt/util.js");
var userInfo=JSON.parse(sessionStorage.getItem("userInfo"));
if(!userInfo){
    location.href="/loginIndex"
}
console.log(userInfo)
var vm = new Vue({
    el:"#choiceList",
    data:{
        loadFlag:false,
        token:"",
        uid:"",//用户id
        isShow:false,
        conversationType:"",
        circleId:"",//好友或者圈子id
        name:"",//好友或者圈子name
        img:"",//好友或者圈子头像
        type:"",//1 好友 2圈子 2消息
        text:"",//聊天内容
        indexs:1,
        userInfo:userInfo,//用户信息
        news:{},//消息
        newsList:[],//消息列表
        newsList1:[],//消息列表
        friendList:{},//好友列表
        circleList:{}, //圈子列表
        dynamicListType:1,
        pageNumber:1,
        friendDynamic:{},//好友动态列表
        friendDynamic1:[],
        friendDynamic2:[],
        messageRecordList:[],//历史聊天记录
        postId:"",  //帖子id
        postInfo:{}, //帖子详情
        relationship:{},
        number:"",
        sourceType:""
    },
    mounted:function(){
        this.searchObject = this.getQueryStringArgs();
        this.number=this.searchObject&&this.searchObject.number;
        this.postId=this.searchObject&&this.searchObject.postId;
        if(this.number==0){  //帖子分享
            this.getPost();
        }else if(this.number==1||this.number==2||this.number==3||this.number==4||this.number==5||this.number==7||this.number==8||this.number==9||this.number==10){     //1乐购商品 2自媒体广告详情3 企业广告视频 4 城市广告  5城市游记6帖子7拼团详情 8爆款活动详情 9 个人名片 10 自媒体商品  11简历
            this.getCouponByCouponId();
        }
        if(this.number==2){
            this.sourceType=this.searchObject&&this.searchObject.sourceType;
        }
        this.getFriendList();
        this.getCircleList();
        // this.getFriendDynamic();
        //localStorage.clear()
        //sessionStorage.clear()
    },
    methods:{
        //后退
        getBack: function () {
           history.go(-1);
        },
        bgimg:function(url){
            url = url?url:"";
            return {
                "background-image":'url("'+url+'"),url("")'
            }
        },
        /*获取查询字符对象*/
        getQueryStringArgs: function () {
            //取得查询字符串并去掉开头的问号
            var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
                args = {},
                items = qs.length ? qs.split("&") : [],
                item = null,
                name = null,
                value = null,
                len = items.length;
            for (var i = 0; i < len; i++) {
                item = items[i].split("=");
                name = item[0];
                value = item[1];
                if (name.length) {
                    args[name] = value;
                }
            }
            return args;
        },
        //tab切换
        getTab:function(num){
            this.indexs=num;
        },
        //获取帖子详情
        getPost:function() {
            var that = this;
            var data = {
                loginUid:that.userInfo.loginUid,
                postId:that.postId
            };
            this.ajax({url: "/friend/getPost", data: data, dataType: "json", method: "post"}, function (b) {
                if (b.json.code == 0 && b.json.data) {
                    that.postInfo= b.json.data;
                    that.getUserRelationship();
                    //console.log(that.categoryList)
                } else {
                    vm.$refs.prompt.toast("获取帖子详情失败！")
                }
            });
        },
        //获取用户关系
        getUserRelationship:function() {
            var that = this;
            var data = {
                loginUid: that.loginUid,
                postId: that.postId
            };
            this.ajax({url: "/friend/getUserRelationship", data: data, dataType: "json", method: "post"}, function (b) {
                if (b.json.code == 0 && b.json.data) {
                    that.relationship=b.json.data;
                    //console.log(that.categoryList)
                    console.log(that.relationship)
                } else {
                    vm.$refs.prompt.toast("获取帖子详情失败！")
                }
            });
        },
        //好友列表
        getFriendList:function(){
            var that=this;
            this.ajax({url:"/friend/getFriendList",data:{loginUid:userInfo.id||that.uid},dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.friendList=b.json.data;
                    //vm.getList(1);
                    //console.log(that.friendList)
                }else{
                    vm.$refs.prompt.toast("获取好友列表失败！")
                }
            });
        },
        //圈子列表
        getCircleList:function(){
            var that=this;
            this.ajax({url:"/friend/getCircleList",data:{loginUid:userInfo.id||that.uid},dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.circleList=b.json.data;
                    vm.getList(1);
                    //console.log(that.circleList)
                }else{
                    vm.$refs.prompt.toast("获取圈子列表失败！")
                }
            });
        },
        //乐购-订单详情
        getCouponByCouponId:function(){
            var that=this,data,url;
            data={};
            if(that.number==1){
                data.loginUid=that.userInfo.loginUid;
                data.productId=that.postId;
                url="/purchase/getProductById";
            }else if(that.number==2){
                data.loginUid=that.userInfo.loginUid;
                data.id=that.postId;
                data.sourceType=that.sourceType;
                url="/selfMedia/getMediaAdvAdvById";
            }else if(that.number==3){
                data.loginUid=that.userInfo.loginUid;
                data.id=that.postId;
                url="/see/getEnterpriseAdvById";
            }else if(that.number==4){
                data.loginUid=that.userInfo.loginUid;
                data.cityAdvId=that.postId;
                url="/cityAd/getCityAdvMediaInfo";
            }else if(that.number==5){
                data.loginUid=that.userInfo.loginUid;
                data.cityAdvId=that.postId;
                url="/cityAd/getCityAdvInfo";
            }else if(that.number==7){
                // data.loginUid=that.userInfo.loginUid;
                data.orderNumber=that.postId;
                url="/purchase/getCollageByOrderNumber";
            }else if(that.number==8){
                data.orderNumber=that.postId;
                data.loginUid=that.userInfo.loginUid;
                url="/purchase/luckyBurstDetail";
            }else if(that.number==9){
                data.loginUid=that.userInfo.loginUid;
                data.id=that.postId;
                url="/user/getUserInfo";
            }else if(that.number==10){
                data.loginUid=that.userInfo.loginUid;
                data.productId=that.postId;
                url="/user/getMediaProductById";
            }
            this.ajax({url:url,data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.coupons=b.json.data;
                    // that.user=that.coupons.list[0];
                }else{
                    vm.$refs.prompt.toast("获取详情失败！")
                }
            });
        },
        //隐藏
        getHide:function(){
            this.isShow=false;
            if(this.searchObject&&this.searchObject.type){
                var path="/friend/circleBar?type="+this.searchObject.type+"&circleId="+this.circleId+"&uid="+this.searchObject.uid;
                location.href=path;
            }
            this.getList(1);
        },
        //显示
        getIsshow:function(list,type){
            var that=this;
            console.log("111111111111")
            console.log(list)
            // return false;
            that.isShow=true;
            that.indexs=1;
            // that.type="";
            that.circleId="";
            that.name="";
            // that.img="";
            that.conversationType="";
            that.messageRecordList=[];
            if(type==1){   //好友
                that.circleId=list.uid;
                that.name=list.name;
                that.img=list.headImg;
                console.log(that.circleId)
                that.conversationType=1;
            }else if(type==2){   //圈子
                console.log("888888888888888888")
                console.log(list)
                if(list.senderUserId==that.userInfo.chatId){
                    that.circleId=that.getHead(1,list.targetId).circleId;
                    that.name=that.getHead(1,list.targetId).circleName;
                }else{
                    that.circleId=list.circleId;
                    that.name=list.circleName;
                }
                console.log(that.circleId)
                that.conversationType=3;
                // console.log(that.circleId+"--"+that.name+"--"+that.img)
            }else if(type==3){  //最近
                console.log(list)
                console.log("3333333333333")
                if(list.senderUserId==that.userInfo.chatId){
                    that.circleId=that.getHead(2,list.targetId).uid;
                    that.name=that.getHead(2,list.targetId).name;
                }else{
                    that.circleId=list.senderUserId;
                    if(list.messageType=="ShareMessage"||list.messageType=="ShopMessage"){
                        that.name=list.content.user.name
                    }else{
                        if(list.content.user){
                            that.name=list.content.user.name;
                        }else{
                            that.name=list.content.message.content.user.name;
                        }
                        //

                    }
                }
                console.log(that.circleId)
                that.conversationType=list.conversationType;
            }
            console.log( this.circleId+"====="+this.name)
            if(that.number==0||that.number==1||that.number==2||that.number==3||that.number==4||that.number==5||that.number==9||that.number==10){
                sendMessage(2);
            }else if(that.number==7||that.number==8){
                sendMessage(3);
            }
            // else if(that.number==3){
            //     sendMessage(4);
            // }
            list.check=false;
            this.messageRecord(2);
            // console.log(that.conversationType+"ddddddddd"+type);

        },
        //发送消息
        getSendMessage:function(){
            if(this.text){
                sendMessage(1);
                this.text="";
            }else{
                vm.$refs.prompt.toast("发送消息不能为空！");
            }
        },
        //历史记录
        getList:function(num){
            console.log("走进历史记录")
            var newList=JSON.parse(localStorage.getItem("newList"));
            if(newList!=null){
                newList.sort(function(a,b){
                    return a.sentTime < b.sentTime;
                });
                //console.log(newList);
                var allArr = [];
                for(var i=newList.length-1;i>=0;i--){
                    var flag = true;
                    for(var j=0;j<allArr.length;j++){
                        if(newList[i].targetId == allArr[j].targetId&&newList[i].conversationType == allArr[j].conversationType){
                            flag = false;
                        }
                    }
                    if(flag){
                        allArr.push(newList[i]);
                    }
                }
                //console.log(allArr);
                if(num==1){
                    allArr.forEach(function(val){
                        val.check=false;
                    });
                }
                this.newsList=allArr;
                console.log("1111111111111111111111111111111");
                console.log(this.newsList);
                this.messageRecord();
            }
            //console.log(this.newsList)
            // this.getIsshow()
        },
        //获取消息记录
        messageRecord:function(){
            this.messageRecordList=[];
            //根据类型和圈子id获取聊天记录
            var key=this.conversationType+"-"+this.circleId;
            var messageRecord=JSON.parse(localStorage.getItem(key));
            console.log("1111111111"+key)
            //根据类型和用户id获取聊天记录
            var uid=userInfo.chatId||this.uid;
            var key1=this.conversationType+"-"+uid;
            var messageRecord1=JSON.parse(localStorage.getItem(key1));
            console.log("22222222222222"+key1)
            var messageAll=[];
            if(messageRecord&&messageRecord1){
                messageRecord1.forEach(function(val){
                    if(val.targetId==vm.circleId){
                        messageAll.push(val);
                    }
                });
                this.messageRecordList=messageRecord.concat(messageAll);
            }else if(messageRecord&&messageRecord1==null){
                this.messageRecordList=messageRecord.concat(messageAll);
            }else if(messageRecord==null&&messageRecord1){
                messageRecord1.forEach(function(val){
                    if(val.targetId==vm.circleId){
                        messageAll.push(val);
                    }
                });
                this.messageRecordList=messageAll;
            }
            this.messageRecordList.sort(function(a,b){
                return a.sentTime > b.sentTime;
            });
            console.log(this.messageRecordList)
        },
        //获取圈子头像名称
        getHead:function(type,id){
            var that=this;
            var vals;
            if(type==1){
                vm.circleList.forEach(function(key){
                    key.list.forEach(function(val){
                        if(val.circleId==id){
                            vals=val;
                        }
                    });
                });
            }else if(type==2){
                vm.friendList.forEach(function(key){
                    key.list.forEach(function(val){
                        if(val.uid==id){
                            vals=val;
                        }
                    });
                });
                console.log(vals)
            }
            return vals;
        },
        getCircleInfo:function(){
            var path="/friend/circleInfo?circleId="+this.circleId+"&uid="+userInfo.id;
            location.href=path;
        },
        getSearch:function(type,item){
           if(type==2){
                console.log(item)
                if(item.content.type==1){  //乐购商品
                    location.href="/purchase/goodsDetails?type=1&productId="+item.content.modelId;
                }else if(item.content.type==2){  //自媒体视频
                    location.href="/see/selfMediaVd?id="+item.content.modelId+"&sourceType="+item.content.extra+"&uid="+userInfo.id||this.uid;
                }else if(item.content.type==3){  //企业广告视频
                    location.href="/see/adDetails?id="+item.content.modelId;
                }else if(item.content.type==4){  //城市广告视频
                    location.href="/cityAd/cityAdVideo?cityAdvId="+item.content.modelId;
                }else if(item.content.type==5){  //城市游记
                    location.href="/cityAd/travelsInfo?cityAdvId="+item.content.modelId;
                }else if(item.content.type==6){  //帖子
                    location.href="/friend/postDetails?postId="+item.content.modelId+"&uid="+userInfo.id||this.uid;
                }else if(item.content.type==8){   //爆款
                    location.href="/purchase/burstingInfo1?type=3&orderNumber="+item.content.orderNumber;   //465464&loginUid=44546
                }else if(item.content.type==7){   //拼团
                    if(item.senderUserId==userInfo.chatId){
                        location.href="/purchase/collageInfo?collageOrderId="+item.content.orderNumber;
                    }else{
                        location.href="/purchase/collageAdd?orderNumber="+item.content.orderNumber
                    }
                }else if(item.content.type==9){   //个人名片
                    location.href="/friend/chatSettings?id="+item.content.modelId;
                }
            }
        }
    }
    ,watch:{
        circleList:function(){
            if(this.searchObject&&this.searchObject.type){
                this.getIsshow(this.circleId,this.searchObject.type);
            }
        },
        news:function(){
            //1 key 1-1    数组 缓存取
            //2 key 1-1    数组[0] key不存在
            //3 key 1-1    数组 push    key 存在
            //4放回缓存中
            var key=vm.news.conversationType+"-"+vm.news.targetId;
            var messages=JSON.parse(localStorage.getItem(key));
            var newList=JSON.parse(localStorage.getItem("newList"));
            var newArr=[];
            var newArrlist=[];
            // debugger;
            if(messages!=null){newArr=messages;}
            if(newList!=null){
                newArrlist=newList;
            }
            // vm.news.check=false;
            newArr.push(vm.news);
            newArrlist.push(vm.news);
            localStorage.setItem(key,JSON.stringify(newArr));
            localStorage.setItem("newList",JSON.stringify(newArrlist));
            //console.log(vm.newsList)
            if(this.isShow){
                this.getList(1);
            }else{
                this.getList();
            }
            // this.$nextTick(function(){
            //     // sideDeleting(".friendIndex-news .news-list a");
            //     //sideDeleting();
            // });
        },
        messageRecordList:function(){
            this.$nextTick(function(){
                var a=document.getElementById("chatPageCent");
                if(this.messageRecordList.length>0&&a!=null){
                    a.scrollTop=a.scrollHeight;
                }
            });
        }
    }
});
startInit();
var instance = null;
function startInit(user,targetId){
    var params = {
        appKey : getValue("appKey"),
        token : getValue("token")||userInfo.token
        // navi : getValue("navi")
    };
    console.log(params)
    var userId = "";
    var callbacks = {
        getInstance : function(instance){
            // 直接初始化
            RongIMLib.RongIMEmoji.init();
            // 通过配置初始化
            var config = {
                size: 24, // 大小, 默认 24, 建议15 - 55
                url: '//f2e.cn.ronghub.com/sdk/emoji-48.png', // 所有 emoji 的背景图片
                lang: 'zh' // 选择的语言, 默认 zh
            };
            RongIMLib.RongIMEmoji.init(config);
        },
        getCurrentUser : function(userInfo){
            console.log(userInfo.userId);
            userId = userInfo.userId;
            console.log("链接成功；userid=" + userInfo.userId);
            document.titie = ("链接成功；userid=" + userInfo.userId);
            //加入聊天室
            //joinChatRoom();
            //发送消息
            //sendMessage();
            //获取单群聊历史消息
            //singleChatInfo()
            //获取会话列表
            //getInstance();
            //checkUnreadMessage();
        }
    };

    initrongyun(params,callbacks);
}
function getValue(id){
    return document.getElementById(id).value;
}
//获取单群聊历史消息
function getInstance(){
    RongIMClient.getInstance().getConversationList({
        onSuccess: function(list) {
            // list => 会话列表集合。
            //console.log(list)
            console.log(JSON.stringify(list))
            console.log("22222222222222222")
            vm.news=list;
        },
        onError: function(error) {
            // do something...
        }
    },null);
}
function initrongyun(params, callbacks, modules){
    var appKey = params.appKey;
    var token = params.token;
    var navi = params.navi || "";
    modules = modules || {};
    var RongIMLib = modules.RongIMLib || window.RongIMLib;
    var RongIMClient = RongIMLib.RongIMClient;
    var protobuf = modules.protobuf || null;
    var config = {};
    //私有云切换navi导航，私有云格式 '120.92.10.214:8888'
    if(navi !== ""){
        config.navi = navi;
    }
    //私有云切换api,私有云格式 '172.20.210.38:81:8888'
    var api = params.api || "";
    if(api !== ""){
        config.api = api;
    }
    //support protobuf url + function
    if(protobuf != null){
        config.protobuf = protobuf;
    }
    var dataProvider = null;
    var imClient = params.imClient;
    if (imClient) {
        dataProvider = new RongIMLib.VCDataProvider(imClient);
    }
    RongIMLib.RongIMClient.init(appKey, dataProvider, config);
    var propertys = ["type","imgSrc","title","source","sex","level","extra","user","modelId","orderNumber"]; // 消息类中的属性名。
    registerMessage("ShareMessage",propertys);
    var propertys1 = ["type","imgSrc","title","discount","pintegral","orderNumber","modelId","extra","user","source"]; // 消息类中的属性名。
    registerMessage("ShopMessage",propertys1);
    // if(vm.number==1){
    //
    // }else if(vm.number==2||vm.number==3){
    //
    // }
    var instance = RongIMClient.getInstance();
    // 连接状态监听器
    RongIMClient.setConnectionStatusListener({
        onChanged: function (status) {
            // console.log(status);
            switch (status) {
                case RongIMLib.ConnectionStatus["CONNECTED"]:
                case 0:
                    console.log("连接成功");
                    callbacks.getInstance && callbacks.getInstance(instance);
                    break;

                case RongIMLib.ConnectionStatus["CONNECTING"]:
                case 1:
                    console.log("连接中");
                    break;

                case RongIMLib.ConnectionStatus["DISCONNECTED"]:
                case 2:
                    console.log("当前用户主动断开链接");
                    break;

                case RongIMLib.ConnectionStatus["NETWORK_UNAVAILABLE"]:
                case 3:
                    console.log("网络不可用");
                    break;

                case RongIMLib.ConnectionStatus["CONNECTION_CLOSED"]:
                case 4:
                    console.log("未知原因，连接关闭");
                    break;

                case RongIMLib.ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"]:
                case 6:
                    console.log("用户账户在其他设备登录，本机会被踢掉线");
                    break;

                case RongIMLib.ConnectionStatus["DOMAIN_INCORRECT"]:
                case 12:
                    console.log("当前运行域名错误，请检查安全域名配置");
                    break;
            }
        }
    });
    /*
    文档：http://www.rongcloud.cn/docs/web.html#3、设置消息监听器
    注意事项：
        1：为了看到接收效果，需要另外一个用户向本用户发消息
        2：判断会话唯一性 ：conversationType + targetId
        3：显示消息在页面前，需要判断是否属于当前会话，避免消息错乱。
        4：消息体属性说明可参考：http://rongcloud.cn/docs/api/js/index.html
    */
    RongIMClient.setOnReceiveMessageListener({
        // 接收到的消息
        onReceived: function (message) {
            // 判断消息类型
            console.log("新消息: " + message.targetId);
            console.log(JSON.stringify(message));
            //console.log("1111111111111111111111")
            message.check=true;
            vm.news=message;
            console.log(vm.news)
            //callbacks.receiveNewMessage && callbacks.receiveNewMessage(message);
        }
    });
    //开始链接
    RongIMClient.connect(token, {
        onSuccess: function(userId) {
            callbacks.getCurrentUser && callbacks.getCurrentUser({userId:userId});
            console.log("链接成功，用户id：" + userId);
        },
        onTokenIncorrect: function() {
            console.log('token无效');
        },
        onError:function(errorCode){
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = '未知错误';
                    break;
                case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
            }
            console.log(errorCode);
        }
    }, '');
    var callback = {
        onSuccess: function(userId) {
            console.log("Reconnect successfully." + userId);
        },
        onTokenIncorrect: function() {
            console.log('token无效');
        },
        onError:function(errorCode){
            console.log(errorcode);
        }
    };
    var configs = {
        // 默认 false, true 启用自动重连，启用则为必选参数
        auto: true,
        // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
        url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
        // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
        rate: [100, 1000, 3000, 6000, 10000]
    };
    RongIMClient.reconnect(callback, configs);
}
//发送文本消息
function sendMessage(num){
    if(num==1){
        var msg = new RongIMLib.TextMessage({
            content:vm.text,
            extra:"",
            user : {
                "id" : vm.userInfo.id,	//不支持中文及特殊字符
                "name" : vm.userInfo.name,
                "portrait" :vm.userInfo.headImg //vm.img
                // "text":""
            }
        });
    }else if(num==2){
        //sendRegisterMessage();
        var content = {
            sex:"",
            level:"",
            extra:"",
            user : {
                "id" : vm.userInfo.id,	//不支持中文及特殊字符
                "name" : vm.userInfo.name,
                "portrait" :vm.userInfo.headImg //vm.img
            }
        };
        if(vm.number==0){    //帖子
            content.type=6;
            content.modelId=vm.postId;
            content.orderNumber=vm.postId;
            content.imgSrc= vm.postInfo.coverImgSrc;
            content.title= vm.postInfo.title;
            content.source="来自帖子";

        }else if(vm.number==1||vm.number==10){
            content.modelId=vm.postId;
            content.orderNumber=vm.postId;
            content.type=vm.number;
            content.imgSrc = vm.coupons.images[0].imgSrc;
            content.title = vm.coupons.title;
            if(vm.number==1){
                content.source = "来自乐购商品";
            }else if(vm.number==10){
                content.source = "来自个人商品";
            }
        }else if(vm.number==2||vm.number==3||vm.number==4||vm.number==5){
            content.modelId=vm.postId;
            content.orderNumber=vm.postId;
            content.type=vm.number;
            content.imgSrc = vm.coupons.coverImgSrc;
            content.title = vm.coupons.title;
            if(vm.number==2){
                content.extra = vm.sourceType;
                content.source = "来自自媒体广告详情";
            }else if(vm.number==3){
                content.source = "来自企业广告视频";
            }else if(vm.number==4){
                content.source = "来自城市广告";
            }else if(vm.number==5){
                content.source = "来自城市游记";
            }
        }else if(vm.number==9){
            content.type=vm.number;
            content.modelId=vm.postId;
            content.orderNumber=vm.postId;
            content.imgSrc = vm.coupons.headImg;
            content.title = vm.coupons.name;
            content.sex = vm.coupons.sex;
            content.level = vm.coupons.level;
            content.source = "来自个人名片";
        }
        var msg = new RongIMClient.RegisterMessage.ShareMessage(content);
    }else if(num==3){
        //sendRegisterMessage();
        var content = {
            // type:2,
            // pintegral:vm.coupons.integral,
            imgSrc: vm.coupons.imgSrc,
            title: vm.coupons.title,
            discount: vm.coupons.discount,
            orderNumber: vm.postId,
            modelId:vm.postId,
            extra: "",
            user : {
                "id" : vm.userInfo.id,	//不支持中文及特殊字符
                "name" : vm.userInfo.name,
                "portrait" :vm.userInfo.headImg //vm.img
                // "text":""
            }
        };
        if(vm.number==7){    //拼团
            content.type=vm.number;
            content.pintegral=vm.coupons.integral;
        }else if(vm.number==8){   //爆款活动
            content.type=vm.number;
            content.pintegral=vm.coupons.pintegral;
        }
        var msg = new RongIMClient.RegisterMessage.ShopMessage(content);
    }
    var conversationtype;
    if(vm.conversationType==1){
        conversationtype= RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可
    }else if(vm.conversationType==3){
        conversationtype = RongIMLib.ConversationType.GROUP; // 群聊,其他会话选择相应的消息类型即可
    }
    console.log(conversationtype)
    var targetId =vm.circleId; // 目标 Id "c6ba28631e514159b1ccade146ea2c06";//
    console.log("targetId="+targetId);
    RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
        onSuccess: function (message) {
            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            console.log(message)
            var key=message.conversationType+"-"+message.senderUserId;
            var messages=JSON.parse(localStorage.getItem(key));
            var newList=JSON.parse(localStorage.getItem("newList"));
            var newArr=[];
            var newArrlist=[];
            // debugger;
            if(messages!=null){
                newArr=messages;
            }
            if(newList!=null){
                newArrlist=newList;
            }
            newArr.push(message);
            newArrlist.push(message);
            localStorage.setItem(key,JSON.stringify(newArr));
            localStorage.setItem("newList",JSON.stringify(newArrlist));
            vm.messageRecord();
            // var mess={
            //     targetId:vm.circleId,
            //     senderUserId:vm.userInfo.id,
            //     content:vm.text
            // };
            // this.messageRecordList.push(JSON.stringify(mess));
            // newArr=JSON.parse(localStorage.getItem(key));
            //console.log(JSON.stringify(newArr));
        },
        onError: function (errorCode,message) {
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = '未知错误';
                    break;
                case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                    info = '在黑名单中，无法向对方发送消息';
                    break;
                case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                    info = '不在讨论组中';
                    break;
                case RongIMLib.ErrorCode.NOT_IN_GROUP:
                    info = '不在群组中';
                    break;
                case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                    info = '不在聊天室中';
                    break;
                default :
                    info = x;
                    break;
            }
            console.log('发送失败:' + info);
        }
    });
}
function checkUnreadMessage(){
    /*
    http://www.rongcloud.cn/docs/web.html#5_5、检测是否有未读的消息
    此接口必须在init()方法之后调用，但不依赖于connect
    只返回true/false，不返回具体的未读数量
    若连接成功后调用此方法将一直返回 false。
    */
    var start = new Date().getTime();
    console.log(token)
    var token=getValue("token")||userInfo.token;
    RongIMClient.getInstance().hasRemoteUnreadMessages(token,{
        onSuccess:function(hasMessage){
            if(hasMessage){
                console.log("有未读的消息")
                // 有未读的消息
            }else{
                console.log("没有未读的消息")
                // 没有未读的消息
            }

            //showResult("检查未读消息成功",hasMessage,start);

        },onError:function(err){
            //showResult("检查未读消息失败",err,start);
        }
    });
}
//定义
function registerMessage(type,propertys){
    var messageName = type; // 消息名称。
    //var objectName = "hkzh:share"; // 消息内置名称，请按照此格式命名 *:* 。
    if(vm.number==0||vm.number==1||vm.number==2||vm.number==3||vm.number==4||vm.number==5||vm.number==9||vm.number==10||vm.number==11){
        var objectName = "hkzh:share"; // 消息内置名称，请按照此格式命名 *:* 。
    }else if(vm.number==7||vm.number==8){
        var objectName = "hkzh:burstingshare"; // 消息内置名称，请按照此格式命名 *:* 。
    }
    var mesasgeTag = new RongIMLib.MessageTag(true,true); //true true 保存且计数，false false 不保存不计数。

    RongIMClient.registerMessageType(messageName,objectName,mesasgeTag,propertys);
}
//自定义消息
function sendRegisterMessage(){
    /*
    文档：http://www.rongcloud.cn/docs/web_api_demo.html#自定义消息
    注意事项：
        1：init之前注册新消息类型
        2：对应接收 onReceived: function (message) {}
            message.messageType == "PersonMessage"
        3：需要自己做解析实现
    */
    /*
       type  类型 1视频，2广告，3游记，4帖子，5圈子，6个人，7城市，8企业，9简历
       imgSrc 封面
       title  标题
       source 来自哪里
       sex  性别
       level  等级
       extra  附加消息
    */
    var propertys = ["type","imgSrc","title","source","sex","level","extra"]; // 消息类中的属性名。
    registerMessage("share",propertys);
    var content = {
        message:{
            content:{
                type:vm.relationship.type,
                imgSrc: vm.postInfo.imgList[0],
                title: vm.postInfo.title,
                source: vm.postInfo.name,
                sex: "1",
                level: 3,
                extra: "",
                user:{
                    id:vm.userInfo.id,
                    portrait:vm.userInfo.headImg,
                    name:vm.userInfo.name
                }
            }
        }
    };

    var msg = new RongIMClient.RegisterMessage.share(content);
    var targetId=2;
    var conversationType= RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可
    RongIMClient.getInstance().sendMessage(conversationType,targetId, msg, {
        onSuccess: function (message) {
            console.log("测试-------------")
            console.log(message)
        },
        onError: function (errorCode) {
        }
    });
}